package com.qqt.csr.web.service;

import cn.hutool.jwt.JWTUtil;
import com.google.common.collect.Maps;
import com.qqt.csr.common.enums.DeviceTypeEnum;
import com.qqt.csr.common.exception.StatusCode;
import com.qqt.csr.common.utils.JsonUtil;
import com.qqt.csr.common.utils.JwtSignerUtil;
import com.qqt.csr.common.utils.ServiceAssert;
import com.qqt.csr.im.entity.Account;
import com.qqt.csr.im.service.AccountService;
import com.qqt.csr.web.dto.member.VisitorInfoDTO;
import com.qqt.csr.web.vo.req.CreatingChannelUserImAccountReqVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

@Slf4j
@Component
public class ImAccountService {
    @Value("${app.socketIODomain}")
    private String imSocketIODomainUrl;

    @Autowired
    private AccountService accountService;

    /**
     * 生成客服im账号用户id
     *
     * @param csId
     * @return
     */
    public String buildCsImUserId(Long csId) {
        if (csId == null) {
            return StringUtils.EMPTY;
        }
        return "CSR" + csId;
    }

    /**
     * 生成访客im账号用户id
     *
     * @param channelId
     * @param userId
     * @return
     */
    public String buildUserImUserId(String channelId, String userId) {
        return "CSR" + channelId + "-" + userId;
    }

    /**
     * 生成访客im账号用户id
     *
     * @param visitorInfoDTO
     * @return
     */
    public String buildUserImUserId(VisitorInfoDTO visitorInfoDTO) {
        return buildUserImUserId(visitorInfoDTO.getChannelId(), visitorInfoDTO.getUserId());
    }


    /**
     * 创建或更新客服im账号信息
     *
     * @param csId
     * @param csName
     * @param csHeadImg
     * @return
     */
    public Account createOrUpdateCsImAccount(Long csId, String csName, String csHeadImg) {
        String csImUserId = this.buildCsImUserId(csId);
        Map<String, String> imAccountExt = Maps.newHashMap();
        imAccountExt.put("csId", String.valueOf(csId));
        imAccountExt.put("userType", "1");
        return accountService.save(csImUserId, csName, csHeadImg, JsonUtil.toJson(imAccountExt));
    }

    /**
     * 创建或更新访客im账号信息
     *
     * @param req
     * @return
     */
    public Account createOrUpdateVisitorImAccount(CreatingChannelUserImAccountReqVO req) {
        String userImUserId = this.buildUserImUserId(req.getChannelId(), req.getChannelUserId());
        Map<String, String> imAccountExt = Maps.newHashMap();
        imAccountExt.put("channelId", req.getChannelId());
        imAccountExt.put("uId", req.getChannelUserId());
        imAccountExt.put("userType", "0");
        Account account = accountService.save(userImUserId, req.getUserName(), req.getHeadImg(), JsonUtil.toJson(imAccountExt));
        ServiceAssert.notNull(account, StatusCode.Common.INTERNAL_SERVER_ERROR);
        return account;
    }

    /**
     * 获取socket.io连接地址
     *
     * @param account
     * @return
     */
    public String getWebsocketAddress(String tenantId, Account account, String deviceFlag, Integer deviceType) {
        if (account == null || StringUtils.isBlank(tenantId)) {
            return StringUtils.EMPTY;
        }
        deviceFlag = Optional.ofNullable(deviceFlag).orElse(account.getId().toString());
        deviceType = DeviceTypeEnum.matchEnum(deviceType).getCode();

        Map<String, Object> payload = Maps.newHashMap();
        payload.put("tenantId", tenantId);
        payload.put("accountId", account.getId());
        payload.put("accountUserId", account.getAccountUserId());
        payload.put("timestamp", System.currentTimeMillis());
        String token = JWTUtil.createToken(payload, JwtSignerUtil.getSigner());
        return String.format("%s?deviceFlag=%s&deviceType=%s&token=%s", imSocketIODomainUrl, deviceFlag, deviceType, token);
    }
}
